<template>
  <el-card class="continer">
    <el-form ref="form" :model="sku" :rules="rules" label-width="80px">
      <el-form-item label="Spu名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>

      <el-form-item label="Sku名称" prop="skuName">
        <el-input v-model="sku.skuName" placeholder="请输入Sku名称" />
      </el-form-item>

      <el-form-item label="Sku价格" prop="price">
        <el-input-number
          class="save-sku-input-number"
          v-model="sku.price"
          controls-position="right"
          :min="1"
          :max="10"
          aria-placeholder="请输入Sku价格"
        />
      </el-form-item>

      <el-form-item label="Sku重量" prop="weight">
        <el-input-number
          class="save-sku-input-number"
          v-model="sku.weight"
          controls-position="right"
          :min="0"
          placeholder="请输入Sku重量"
        />
      </el-form-item>

      <el-form-item label="Sku描述" prop="skuDesc">
        <el-input
          v-model="sku.skuDesc"
          type="textarea"
          placeholder="请输入Sku描述"
        />
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row>
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
          >
            <el-form-item label="attr.attrName">
              <el-select
                placeholder="请选择平台属性"
                v-model="sku.skuAttrValueList[index]"
              >
                <el-option
                  v-for="attrValue in attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row>
          <el-col
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
          >
            <el-form-item :label="saleAttr.saleAttrName">
              <el-select
                v-model="sku.skuSaleAttrValueList[index]"
                placeholder="请选择销售属性"
              >
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="Sku图片" prop="skuImageList">
        <el-table
          :data="spuImageList"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img class="save-ksu-img" :src="row.imgUrl" :alt="row.imgName" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称"></el-table-column>
          <el-table-column label="操作">
            <template>
              <el-button
                v-if="row.isDefault === '1'"
                type="success"
                size="mini"
                disabled
              >
                默认图片
              </el-button>
              <el-button
                v-else
                type="primary"
                size="mini"
                @click="setSkuDefaultImg(row)"
              >
                设置默认图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <button @click="$emit('setIsShow', 1)">取消</button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: "SaveSku",
  props: {
    spu: {
      type: Object
    }
  },
  data() {
    const skuImageListValidator = (rule,value,callback) => {
      if (!value.length) {
        callback('至少选中一张图片')
        return
      }

      if (!value.some(img.isDefault === '1')) {
        callback('必须设置并选中默认图片')
        return
      }

      callback()
    }

    const skuSaleAttrValueListValidator = (rule, value,callback) => {
      if(!value.length) {
        callback('至少选中一个销售属性')
        return
      }

      callback()
    }

    return {
      attrList: [],
      spuSaaleAttrList: [],
      spuImageList: [],
      sku: {
        skuName: '',
        price: 0,
        weight: 0,
        skuDesc: '',
        skuAttrValueList: [],
        skuSaleAttrValueList : [],
        skuImageList: []
      },
      rules: {
        skuName: [
          { reqired: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur'}],
        weight: [{ required: true, message: '请输入SKU重量', trigger: 'blur'}],
        skuDesc: [
          { reqired: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        // 平台属性列表
        skuAttrValueList: [{ required: true}],
        // 销售属性列表
        skuSaleAttrValueList: [
          { required: true, validator: skuSaleAttrValueListValidator}
        ],
        // 图片列表
        skuImageList: [{ required: true, validator:skuImageListValidator}]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  async mounted() {
    const {
      category1Id,
      category2Id,
      category3Id,
      spu: {id}
    } = this

    const [
      attrListResponse,
      spuSaleAttrListResponse,
      spuImageListResponse
    ] = await Promise.allSettled([
      this.$API.attr.reqGetAttrList({
        category1Id,
        category2Id,
        category3Id,
      }),
      this.$API.spu.reqGetSpuSaleAttrList(id),
      this.$API.spu.reqGetSpuImageList(id),
    ])
    if (attrListResponse.status === 'fulfilled') {
      this.attrList = attrListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取平台属性列表失败'
      })
    }

    if (spuSaleAttrListResponse.status === 'fulfilled') {
      this.spuSaleAttrList = spuSaleAttrListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取销售属性列表失败'
      })
    }

    if (spuImageListResponse.status === 'fulfilled') {
      this.spuImageList = spuImageListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取SPU图片列表失败'
      })
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 收集表单数据
          const {
            skuName,
            price,
            weight,
            skuDesc,
            skuAttrValueList,
            skuSaleAttrValueList,
            skuImageList
          } = this.sku

          const { category3Id } = this
          const { id } = this.spu

          const skuDefaultImg = skuImageList.find(img => img.isDefault === '1')
            .imgUrl

          // 发送请求
          await this.$API.sku.reqSaveSku({
            skuName,
            price,
            weight,
            skuDesc,
            // skuAttrValueList skuSaleAttrValueList 有可能有undefined
            skuAttrValueList: skuAttrValueList.filter(Boolean).map(val => {
              const [attrId, attName, valueId, valueName] = val.split(':')
              return {
                attrId,
                attName,
                valueId,
                valueName
              }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList
              .filter(Boolean)
              .map(val => {
                const [
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                ] = val.split(':')
                return {
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                }
              }),
            skuImageList,
            skuDefaultImg,
            category3Id,
            spuId: id
          })
          // 提示并返回
          this.$emit('setIsShow', 1)
          this.$message({
            type: 'success',
            message: '添加SKU成功'
          })
        }
      })
    },
    // 选择图片触发
    handleSelectionChange(val) {
      this.sku.skuImageList = val;
    },
    // 设置默认图片
    setSkuDefaultImg(row) {
      // 将其他的设为0
      this.spuImageList.forEach(img => {
        this.$set(img, 'isDefault', '0')
      })
      // 将当前点击的设为1
      this.$set(row, 'isDefault', '1')
    }
  },
};
</script>

<style lang="sass" scoped>
.save-sku-img
  width: 150px
  height: 100px
.save-sku-input-number
  width: 100px
</style>
